<template>
	<div class="game-header">
		<h1 class="title">LeetyCanFly's 2048</h1>
		<p class="score">得分：{{ score }}</p>
		<div :class="['add-score', animClass]">{{ showAddScore }}</div>
		<a class="reset-start"
		   @click="resetStart"
		   href="javascript:">重新开始</a>
		<a v-show="showBackStep"
		   href="javascript:"
		   class="back-step"
		   @click="backStep">回退一步</a>
	</div>
</template>

<script>
	export default {
		name: "GameHeader",
		data() {
			return {
				addScore: 0,
				animClass: '',
				animTimer: null
			}
		},
		methods: {
			resetStart() {
				this.$store.commit('init')
				this.$emit('resetStart')
			},
			backStep() {
				if (this.showBackStep) {
					if (this.addScore > 0) {
						this.$store.commit('awarded', -this.addScore)
					}
					this.$emit('backStep')
				}
			}
		},
		computed: {
			score() {
				return this.$store.state.score
			},
			showAddScore() {
				if (this.addScore > 0) {
					return '+' + this.addScore
				}
				return this.addScore
			},
			showBackStep() {
				return this.$store.state.beforeMoveTiles.length > 0
					&& this.$store.state.winning === 0
			}
		},
		watch: {
			score: {
				handler(newValue, oldValue) {
					/**
					 * 得分动画
					 */
					if (newValue) {
						this.addScore = newValue - oldValue
						if (this.animClass) {
							if (this.animTimer) clearTimeout(this.animTimer)
							this.animClass = ''
						}
						this.animClass = 'score-anim'
						this.animTimer = setTimeout(() => this.animClass = '', 800)
					}
				}
			}
		}
	}
</script>

<style scoped>
	@media screen and (max-width: 520px) {
		#app .reset-start {
			right: 30px;
			bottom: 32px;
			z-index: 10;
		}

		#app .back-step {
			padding: 0;
			font-size: 14px;
			height: 30px;
			line-height: 30px;
			left: 30px;
			bottom: 32px;
			z-index: 10;
		}

		#app .add-score {
			right: 90px;
			bottom: 6px;
			z-index: 99;
		}
	}

	.game-header {
		position: relative;
	}

	.reset-start:hover {
		color: #eee4da;
	}

	.score {
		font-weight: bold;
	}

  h1{
    color: #183178;
  }
	.reset-start {
		position: absolute;
		right: 0;
		bottom: 0;
	}

	.add-score {
		position: absolute;
		right: 200px;
		bottom: 6px;
		font-weight: bold;
		color: #e74c3c;
		opacity: 0;
	}

	.back-step {
		background-color: #183178;
		border-radius: 3px;
		padding: 0 20px;
		text-decoration: none;
		color: #f9f6f2;
		width: 100px;
		height: 40px;
		line-height: 42px;
		text-align: center;
		user-select: none;
		cursor: pointer;
		position: absolute;
		left: 0;
		bottom: 0;
	}

	.score-anim {
		animation: anim-add 800ms;
	}

	@keyframes anim-add {
		0% {
			opacity: 1;
			bottom: 6px;
		}
		50% {
			opacity: .5;
		}
		100% {
			bottom: 60px;
			opacity: 0;
		}
	}
</style>